<script setup>
import api from '@/api'
import { Message } from '@arco-design/web-vue'
import { ref, reactive, watch, nextTick, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import UploadFile from '@/components/uploadFile.vue'
import UploadImage from '@/components/uploadImage.vue'
import { IconSearch } from '@arco-design/web-vue/es/icon'

const $route = useRoute()
const $router = useRouter()

const title = ref('')
const listData = ref([])
const pageVal = ref(1)
const pageSize = ref(10)
const listTotal = ref(0)
// 评价人员搜索
const keyword = ref('')
const status = ref('')

// 评价人员列表
const userLists = ref([])

// 评价人员状态列表
const StatusList = ref([
  {
    name: '待评价',
    value: 1,
  },
  {
    name: '已评价',
    value: 2,
  },
])

// 部门数据
const departments = ref([])

// 岗位数据
const posts = ref([])

// 评价详情
const form = reactive({
  departments: '',
  departments_id: '',
  posts: '',
  posts_id: '',
  post_ask: '',
  recruit_number: '',
  // muban: '',
  admission_number: '',
  interview_number: '',
})

// const formRules = {
//   departments_id: [
//     {
//       required: true,
//       message: '请选择部门',
//     }
//   ],
//   posts_id: [
//     {
//       required: true,
//       message: '请选择岗位',
//     }
//   ],
//   recruit_number: [
//     {
//       required: true,
//       message: '请输入评价人数',
//     },
//     {
//       type: 'number',
//       min: 1,
//       message: '评价人数不能小于1人',
//     }
//   ],
//   post_ask: [
//     {
//       required: true,
//       message: '请输入岗位要求',
//     }
//   ],
//   admission_number: [
//     {
//       required: true,
//       message: '请输入录取人数',
//     },
//     {
//       type: 'number',
//       message: '录取人数必须为数字',
//     }
//   ],
//   interview_number: [
//     {
//       required: true,
//       message: '请输入面试人数',
//     },
//     {
//       type: 'number',
//       message: '面试人数必须为数字',
//     }
//   ]
// }

// 评价模板
const templates = ref([])

// const addSon = (rowIndex) => {
//   data.value[rowIndex].son.push({
//     wenti: '问题2',
//     yaodian: '要点1',
//     putong: 1,
//     lianghao: 3,
//     youxiu: 5,
//   })
// }

// const deleteSon = (rowIndex, index) => {
//   data.value[rowIndex].son.splice(index, 1)
// }

// const addItem = () => {
//   data.value.push({
//     bankuai: '',
//     son: [
//       {
//         wenti: '',
//         yaodian: '',
//         putong: 1,
//         lianghao: 3,
//         youxiu: 5,
//       },
//     ],
//   })
// }

// const deleteItem = (rowIndex) => {
//   data.value.splice(rowIndex, 1)
// }

const toJump = (url) => {
  console.log('router', $router.push(url))
  $router.push(url)
}

// const handleSubmit = (data) => {
//   console.log(data)
// }

const visible = ref(false)
const form1 = reactive({
  name: '',
  mobile: '',
  email: '',
  biographical_notes: '',
  channel: '',
})

const form1Rules = {
  name: [
    {
      required: true,
      message: '请输入姓名',
    },
  ],
  // mobile: [
  //   {
  //     required: true,
  //     message: '请输入手机号',
  //   },
  //   {
  //     pattern: /^1[3-9]\d{9}$/,
  //     message: '请输入正确的手机号',
  //   },
  // ],
  // email: [
  //   {
  //     required: true,
  //     message: '请输入邮箱',
  //   },
  //   {
  //     type: 'email',
  //     message: '请输入正确的邮箱',
  //   },
  // ],
  // biographical_notes: [
  //   {
  //     required: true,
  //     message: '请上传简历',
  //   },
  // ],
}

const form1Ref = ref(null)

const handleForm1Submit = async () => {
  console.log('新增评价人员')
  form1Ref.value.validate(async (vaild) => {
    const formData = {
      name: form1.name,
      mobile: form1.mobile,
      email: form1.email,
      channel: form1.channel,
      biographical_notes: form1.biographical_notes,
      recuit_plan_id: $route.query.id,
      image: form1.image,
    }
    const res = await api.post('/recruit/createApplication', formData)
    if (res.code == 200) {
      Message.success('提交成功')
      visible.value = false
      getYingpinUsers()
    } else {
      Message.error(res.message)
    }
  })
}

// const handleClick = () => {
//   visible.value = true
// }
// const handleBeforeOk = (done) => {
//   console.log(form)
//   window.setTimeout(() => {
//     done()
//     // prevent close
//     // done(false)
//   }, 3000)
// }
const handleCancel = () => {
  visible.value = false
}

// 停止评价
const stopRecruit = async () => {
  console.log('停止评价')
  const res = await api.get(`/evaluate/evaluateEnds?plan_id=${$route.query.id}`)
  if (res.code == 200) {
    Message.success('已停止评价')
    toJump('/evaluate/plansList')
  } else {
    Message.error(res.message)
  }
}

// const getUserStatusList = async () => {
//   const res = await api.get(
//     `/recruit/statusList?recuit_plan_id=${$route.query.id}`
//   )
//   StatusList.value = res.data
// }

// // 保存修改
// const savePlans = async () => {
//   console.log('保存评价计划', form)
//   const formData = {
//     departments_id: form.departments_id,
//     posts_id: form.posts_id,
//     recruit_number: form.recruit_number,
//     post_ask: form.post_ask,
//     recruit_template_id: '',
//     plan_id: $route.query.id
//   }
//   let url = '/recruit/updatePlan'
//   const res = await api.post(url, form)
//   if (res.code == 200) {
//     Message.success('保存成功')
//     toJump('/recruit/plans/index')
//   } else {
//     Message.error(res.message)
//   }
// }

// 获取评价计划详情
const getDetail = async () => {
  console.log('获取评价计划详情', form)
  const res = await api.get(
    `/evaluate/evaluatePlanDetails?plan_id=${$route.query.id}`
  )
  // form = reactive(res.data)
  form.id = res.data.id
  form.departments_id = res.data.departments_id
  form.departments = res.data.departments
  form.posts = res.data.posts
  form.posts_id = res.data.posts_id
  form.post_ask = res.data.post_ask
  form.recruit_number = res.data.recruit_number + ''
  form.admission_number = res.data.admission_number + ''
  form.residue_number = res.data.residue_number + ''
  form.interview_number = res.data.interview_number + ''

  console.log('form', form)
}

// 获取计划关联的评价模板
const getRecruitTemplate = async () => {
  const res = await api.get(
    `/evaluate/planTemplateDetails?plan_id=${$route.query.id}`
  )
  templates.value = res.data
}

// 获取评价人员列表
const getYingpinUsers = async () => {
  console.log('获取评价人员列表')
  const res = await api.get(
    `/recruit/applicationList?keyword=${keyword.value}&status=${status.value}&recuit_plan_id=${$route.query.id}`
  )
  userLists.value = res.data
}

// 部门列表
const getDepartments = async () => {
  console.log('获取部门列表')
  const res = await api.get('/evaluate/departmentsList')
  departments.value = res.data
  if (res.data.length > 0) {
    getPosts(res.data[0].id)
  }
}

// 岗位列表
const getPosts = async (departId) => {
  console.log('获取岗位列表' + departId)
  const res = await api.get(`/evaluate/postsList?department_id=${departId}`)
  posts.value = res.data
}

const getMyEvaluateList = async (page) => {
  try {
    const res = await api.get('evaluate/myEvaluateList', {
      params: {
        plan_id: $route.query.id,
        page,
        pageSize: pageSize.value,
        user_name: keyword.value,
        status: status.value,
      },
    })
    console.log('res', res)
    listData.value = res.data.items
    listTotal.value = res.data.pageInfo.total
    pageVal.value = page
  } catch (error) {
    console.error(error)
  }
}

const init = async () => {
  console.log('加载收据')
  // getUserStatusList()
  await getDepartments()
  // 获取详情和评价人员列表
  getDetail()
  // getRecruitTemplate()
  // getYingpinUsers()
  getMyEvaluateList(1)
}

watch(
  () => form.departments_id,
  (newVal) => {
    console.log('change departments_id', newVal)
    posts.value = []
    // form.posts_id = ''
    getPosts(newVal)
  }
)

init()

const handleUpload = (file, fileList) => {
  console.log('upload file', file, fileList)
  form1.biographical_notes = file
}
</script>

<template>
  <div class="page">
    <div class="header">评价计划详情</div>

    <div class="record_body"
         style="padding: 20px 24px 0">
      <div class="form_body">
        <div class="flex at_c jc_b mb20">
          <div class="form_body_title">评价信息</div>
          <a-space>
            <a-button v-if="!listData.length"
                      @click="
                toJump('/evaluate/addPlans?plan_id=' + $route.query.id)
              "
                      type="primary">修改</a-button>
            <a-button v-else
                      @click="stopRecruit"
                      type="primary"
                      status="danger">评价结束</a-button>
          </a-space>
        </div>

        <a-form auto-label-width
                :model="form">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="departments_id"
                           label="所属部门">
                <!-- <a-select readonly v-model="form.departments_id"
                          placeholder="请选择评价部门"
                          allow-clear>
                  <a-option v-for="(item, index) in departments" :key="index" :value="item.id">{{ item.name }}</a-option>
                </a-select> -->
                <a-input readonly
                         v-model="form.departments"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="posts_id"
                           label="岗位名称">
                <!-- <a-select readonly v-model="form.posts_id"
                          placeholder="请选择评价岗位名称"
                          allow-clear>
                  <a-option v-for="(item, index) in posts" :key="index" :value="item.id">{{ item.name }}</a-option>
                </a-select> -->
                <a-input readonly
                         v-model="form.posts"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <!-- <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item field="post_ask" label="岗位要求">
                <a-textarea
                  readonly
                  v-model="form.post_ask"
                  placeholder="请输入岗位要求"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row> -->
          <a-row :gutter="24">
            <!-- <a-col :span="12">
              <a-form-item field="interview_number" label="面试轮数">
                <a-input
                  readonly
                  v-model="form.interview_number"
                  placeholder="请输入面试轮数"
                />
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item field="muban"
                           label="评价模板">
                <a-button @click="
                    toJump(
                      '/evaluate/evaluateTemplate?plan_id=' +
                        $route.query.id
                    )
                  "
                          type="primary">查看详情</a-button>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <!-- <a-col :span="8">
              <a-form-item field="recruit_number" label="评价需求数量">
                <a-input
                  readonly
                  v-model="form.recruit_number"
                  placeholder="请输入评价需求数量"
                />
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item field="recruit_number"
                           label="评价人数">
                <a-input readonly
                         v-model="form.recruit_number"
                         placeholder="请输入已评价人数" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="residue_number"
                           label="当前剩余人数">
                <a-input readonly
                         v-model="form.residue_number"
                         placeholder="请输入当前评价人数" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>

    <a-divider />

    <div class="record_body"
         style="padding: 0 24px 20px">
      <div class="form_body">
        <div class="flex at_c jc_b mb20">

          <a-space>
            <a-select v-model="status"
                      placeholder="筛选状态">
              <a-option value="">选择状态</a-option>
              <a-option v-for="item in StatusList"
                        :value="item.value"
                        :key="item.value">{{ item.name }}</a-option>
            </a-select>
            <a-input-search :style="{ width: '320px' }"
                            v-model="keyword"
                            placeholder="名称模糊查询"
                            button-text="查询"
                            @search="getMyEvaluateList(1)"
                            search-button
                            allow-clear />
          </a-space>
        </div>

        <a-table :data="listData"
                 @page-change="getMyEvaluateList"
                 :pagination="{
                  showTotal: true,
                  size: 'small',
                  total: listTotal,
                  pageSize: pageSize,
                  current: pageVal,
                }">
          <template #columns>
            <a-table-column title="序号"
                            :width="60">
              <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
            </a-table-column>
            <a-table-column title="评价对象"
                            data-index="user_name"></a-table-column>
            <a-table-column :sortable="{ sortDirections: ['ascend', 'descend'] }"
                            title="预约评价时间"
                            data-index="evaluate_time"></a-table-column>
            <a-table-column :sortable="{ sortDirections: ['ascend', 'descend'] }"
                            title="评价状态">
              <template #cell="{ record }">
                <div v-if="record.status==1">待评价</div>
                <div v-if="record.status==2">已评价</div>
              </template>
            </a-table-column>
            <a-table-column title="操作"
                            align="right"
                            :width="200">
              <template #cell="{ record }">
                <a-space>
                  <a-button v-if="record.status == 1"
                            type="primary"
                            size="mini"
                            @click="
                  toJump(
                    `/evaluate/myEvaluateDetails?evaluate_id=${record.id}&type=1`
                  )
                ">开始评价</a-button>
                  <a-button v-if="record.status == 2"
                            type="primary"
                            size="mini"
                            @click="
                  toJump(
                    `/evaluate/myEvaluateDetails?evaluate_id=${record.id}`
                  )
                ">评价详情</a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal v-model:visible="visible"
             title="新增应聘人员"
             @cancel="handleCancel"
             :footer="false">
      <a-form ref="form1Ref"
              :model="form1"
              :rules="form1Rules"
              @submit="handleForm1Submit">
        <a-form-item field="name"
                     label="应聘者姓名">
          <a-input v-model="form1.name"
                   placeholder="请输入应聘者姓名" />
        </a-form-item>
        <a-form-item field="mobile"
                     label="联系电话">
          <a-input v-model="form1.mobile"
                   placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item field="image"
                     label="图像"
                     help="请上传jpg、png、gif格式图片、文件大小不能超过1MB"
                     validate-trigger="input">
          <uploadImage v-model="form1.image"
                       width="100px"
                       height="100px"></uploadImage>
        </a-form-item>
        <a-form-item field="biographical_notes"
                     label="上传简历">
          <UploadFile dir="plans/biographical_notes"
                      :maxSize="1"
                      @change="handleUpload"
                      :accepts="[
              '.doc',
              '.docx',
              '.pdf',
              'image/*',
              'image/jpeg',
              'image/png',
              'image/jpg',
              'application/pdf',
              'application/msword',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            ]" />
        </a-form-item>
        <a-form-item v-if="form1.biographical_notes">
          <!-- 超出换行 -->
          <a-row style="display: block; width: 100%; word-break: break-all">{{
            form1.biographical_notes
          }}</a-row>
        </a-form-item>
        <a-form-item field="email"
                     label="联系邮箱">
          <a-input v-model="form1.email"
                   placeholder="请输入联系邮箱" />
        </a-form-item>
        <a-form-item field="channel"
                     label="渠道">
          <a-input v-model="form1.channel"
                   placeholder="请输入渠道" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary"
                      status="danger"
                      @click="visible = false">取消</a-button>
            <a-button type="primary"
                      @click="handleForm1Submit">提交</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page {
  height: 95%;
  border-bottom: 0;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

:deep(.arco-table-cell):has(.diytd) {
  padding: 0;
}
:deep(.arco-table-cell):has(.diytd) .diytd {
  padding: 0.6rem 1.06667rem;
  border-bottom: 1px solid #ddd;
}
:deep(.arco-table-cell):has(.diytd) .diytd:last-child {
  border: none;
}

.h32 {
  height: 32px;
  display: flex;
  align-items: center;
}

.record_body {
  box-sizing: border-box;
  padding: 20px 24px;
}

.form_body {
  box-sizing: border-box;
  padding: 20px 24px;
  background-color: #fff;
  margin-bottom: 20px;
}

.form_body_title {
  font-size: 18px;
  font-weight: bold;
}
</style>
